package com.lance.answer.gui;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import com.alibaba.fastjson.JSONObject;
import com.lance.answer.gui.answer.AnswerMulptliUser;
import com.lance.answer.gui.answer.AnswerObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main2
     */
    public Main() {
        initComponents();
    }

    // Variables declaration - do not modify
    private javax.swing.JButton startButton;

    private JLabel userNameLabel;
    private JLabel passwordLabel;
    private JLabel subjectCode;
    private JLabel driverPath;
    private JLabel timeoutLabel;
    private JTextField timeoutField;
    private JTextField userNameField;
    private JTextField passwordField;
    private JTextField subjectCodeField;
    private JTextField driverPathField;

    // End of variables declaration


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        this.setTitle("么么哒答题系统V1.0");
        userNameLabel = new JLabel("用户名");
        passwordLabel = new JLabel("密码");
        subjectCode = new JLabel("课程编码");
        //driverPath = new JLabel("驱动路径");
        timeoutLabel =  new JLabel("页面超时设置:");
        userNameField = new JTextField("2065001457568");
        passwordField = new JTextField("19990205");
        subjectCodeField = new JTextField("基础会计");
        //driverPathField = new JTextField();
        timeoutField = new JTextField();
        timeoutField.setColumns(8);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);



        startButton = new javax.swing.JButton();
        startButton.setText("开始答题");
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    startButtonAction(evt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(52, 52, 52)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(userNameLabel)
                                        .addComponent(userNameField)
                                        .addComponent(passwordLabel)
                                        .addComponent(passwordField)
                                        .addComponent(subjectCode)
                                        .addComponent(subjectCodeField)
                                        /* .addComponent(driverPath)
                                         .addComponent(driverPathField)*/
                                        .addComponent(startButton)
                                )

                        )
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(userNameLabel)
                                .addGap(18 ,18 ,18)
                                .addComponent(userNameField)
                                .addGap(54, 54, 54)
                                .addComponent(passwordLabel)
                                .addGap(18 ,18 ,18)
                                .addComponent(passwordField)
                                .addGap(54, 54, 54)
                                .addComponent(subjectCode)
                                .addGap(18 ,18 ,18)
                                .addComponent(subjectCodeField)
                                .addGap(54, 54, 54)
                                /* .addComponent(driverPath)
                                 .addGap(18 ,18 ,18)
                                 .addComponent(driverPathField)
                                 .addGap(54, 54, 54)*/
                                .addComponent(startButton)
                                .addContainerGap(123, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>


    private void startButtonAction(ActionEvent evt) throws Exception {
        //startTask();
        startAnswer();
    }

    private void startAnswer() throws Exception {
        String subjectCode = this.subjectCodeField.getText();
        //String driverPath = this.driverPathField.getText();
        String userName = this.userNameField.getText();
        String password = this.passwordField.getText();
        if (StringUtils.isNotBlank(subjectCode)) {
            subjectCode = subjectCode.trim();
        }
       /* if (StringUtils.isNotBlank(driverPath)) {
            driverPath = driverPath.trim();
        }*/
        if (StringUtils.isNotBlank(userName)) {
            userName = userName.trim();
        }
        if (StringUtils.isNotBlank(password)) {
            password = password.trim();
        }
        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectCode + "/" + subjectCode +".answer");
        String answerStr = IOUtils.toString(inputStream);

/*
        File file = new File("/Users/guiliangzhou/IdeaProjects/answerTool/src/main/resources/" + subjectCode + "/" + subjectCode +".answer");
        String answerStr = FileUtils.readFileToString(file,"utf-8");
*/
        List<AnswerObject> list = JSONObject.parseArray(answerStr,AnswerObject.class);
        Map<String,AnswerObject> map = new HashMap<>();
        for (AnswerObject answerObject:list) {
            map.put(answerObject.getQuestionCode(),answerObject);
        }

        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectCode + "/" + subjectCode +".section");
        List<String> list1 = IOUtils.readLines(inputStream3);
        List<String> paths = new ArrayList<>();
        for (String str:list1) {
            paths.add(str.split(",")[0]);
        }
        AnswerMulptliUser.answer(paths,map,subjectCode,null,userName,password);
    }



    public void setDesktopIfWindows(JFileChooser chooser){
        chooser.setCurrentDirectory(new File(System.getenv("HOME") + "/Desktop"));
        chooser.setDragEnabled(true);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
}

